/** 
 * 入参
    state：1-指令   2-新增簿记
 * 出参
    点击“指令下达”或“保存”成功后，抛出onOK事件；
   点击“取消”按钮，抛出onCancle事件。
*/
import React, { PureComponent } from 'react';
import { PrimaryC, NoDataMaskC, FirstHeaderC, PrimaryGhostC, ModalC, TableC } from '../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Tabs, Spin, message, Modal } from 'antd';
import style from './index.less';
import CurrentAsset from './CurrentAsset.js';
import SaveOrder from './SaveOrder';
import WithdrawnOrder from './WithdrawnOrder';
import CalcInterestOrder from './CalcInterestOrder';
import { uniqueKey } from '../../../utils/commonFunc';
import Hold from './Hold.js';
import config from './config';
const confirm = Modal.confirm;
import { connect } from 'dva';
import 'moment/locale/zh-cn';
import moment from 'moment';
const { TabPane } = Tabs;
@Form.create()
@connect(({ depositOrderM, userM: user, globalM, loading, trailM, isAccountConfiguredM }) => ({
  depositOrderM,
  user,
  globalM,
  loading,
  trailM,
  errorSetMsg: isAccountConfiguredM.msg,
}))
export default class AddNew extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      timeStamp: new Date().getTime(), //时间戳
      productId: undefined, //当前产品id
      fundCode: undefined, //当前组合id
      fundCodeSave: undefined, //存入指令组合id,
      fundCodeWithdrawn: undefined, //支取指令组合id
      fundCodeCalc: undefined, //结息指令组合id
      productIdSave: undefined, //存入指令产品id,
      productIdWithdrawn: undefined, //支取指令产品id
      productIdCalc: undefined, //结息指令产品id
      instructType: 'F', //当前tab  //"F" 存入 "i" 支取  "calc" 结息
      typeList: config.typeList, //存款类型
      saveOrderInfo: undefined, //存入指令的详情信息
      withdrawnInfo: undefined, //支取指令的详情信息
      calcInterestInfo: undefined, //结息指令的详情信息
      flag: true, // 蒙版
      trailColumns: [], //试算结果列表
      trailDataSource: [], //试算结果数据
      trailModel: false, //试算模态框
      vcBankName: undefined,
      productCode: undefined, //产品code
      portfolioCode: undefined, //组合code
      headBankList: [], // 存款总行
      uid: '',
    };
  }
  //state：1-指令   2-新增簿记
  //存款类型、存款总行、当前组合ID、存入指令组件的组合ID、支取指令的组合ID、结息指令的组合ID、时间戳、存入指令组件对象、支取指令组件对象、结息指令组件对象
  //响应存入组件组合变更事件、响应支取组件组合变更事件、响应持仓组件组合变更事件、响应当前持仓组件双击事件
  componentDidMount() {
    const uid = uniqueKey();
    uid.then((r) => {
      this.setState({ uid: r });
    });
  }

  UNSAFE_componentWillReceiveProps(nextProps) {}

  //获取持仓双击事件 抛出的指令相关详情
  holdClick = (info) => {
    const { instructType } = this.state;
    if (instructType == 'F') {
      this.setState({
        saveOrderInfo: info,
      });
    } else if (instructType == 'i') {
      //判断是否提前支取
      if (info.isAdvanceInterest != 0) {
        message.warning('该存款不可提前支取!');
        return;
      }
      this.setState({
        withdrawnInfo: info,
      });
    } else {
      // //判断存款类型是不是活期
      if (info.depositType != '00') {
        message.warning('该存款不支持结息!');
        return;
      }
      this.setState({
        calcInterestInfo: info,
      });
    }
  };
  //获取组合id
  getFundCode = (id, type) => {
    if (id) {
      this.setState({
        flag: false,
      });
    } else {
      this.setState({
        flag: true,
      });
    }
    const { fundCode } = this.state;
    //tab切换时，拿激活的tab的组合ID与当前组合ID相比较，如果不一样，则更新当前组合ID
    this.setState({
      [type]: id,
    });
    if (id !== fundCode) {
      this.setState({
        fundCode: id,
      });
    }
  };
  //获取产品id
  getProductCode = (id, type) => {
    const { productId } = this.state;
    this.setState({
      [type]: id,
    });
    if (id !== productId) {
      this.setState({
        productId: id,
      });
    }
  };
  //指令下达 簿记保存 获取form表单数据并校验
  confirmClick = () => {
    const { instructType } = this.state;
    if (instructType == 'F') {
      //存
      if (!this.SaveOrder.state.isCanOrder && this.props.state == 1) {
        //在点击“下达”时，若标记指示未配置指令，则提示用户“该组合为配置指令，无法下发指令。
        message.warning(this.props.errorSetMsg);
        return;
      }
      if (this.props.state != 10) {
        var T0 = this.CurrentAsset.state.assetObj.T0 || 0;
      }
      this.SaveOrder.formContent.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          if (this.props.state == 10) {
            this.orderSave(values);
            return; //交易录入不做校验
          }
          if (values.bankDepositBalance > T0) {
            message.error('存款金额不能大于T+0资金');
            return;
          }
          this.orderSave(values);
        }
      });
    } else if (instructType == 'i') {
      //取
      this.WithdrawnOrder.formContent.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          if (values.bankDrawDownBalance > values.bankDepositBalance) {
            message.error('支取本金不能大于存入金额');
            return;
          }
          this.orderSave(values);
        }
      });
    } else {
      //结息
      this.calcInterestOrder.formContent.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          if (values.bankDrawDownBalance > values.bankDepositBalance) {
            message.error('结息金额不能大于存入金额');
            return;
          }
          this.orderSave(values);
        }
      });
    }
  };
  //指令下达 簿记保存请求后台
  orderSave = (params) => {
    const { instructType, withdrawnInfo, calcInterestInfo } = this.state;
    const {
      user: { currentUser = {} },
    } = this.props;
    const {
      globalM: {
        dataDictionary: { C_CUSTODIAN = [] },
      },
      state,
    } = this.props;
    let url = state == 1 ? 'depositOrderM/orderSave' : state == 2 ? 'depositOrderM/tradeBookSave' : state == 11 ? 'portfolioTrialAddM/addNewSave' : 'depositOrderM/tradeAdd';

    let args = {}; //支取 结息的时候需要存款编号、相关存款的id
    if (instructType == 'i') {
      args.bankDepositNumber = withdrawnInfo.pid;
      params.earlyDrawdownDate = moment(params.earlyDrawdownDate).format('YYYYMMDD');
      if (state == 10) {
        //交易录入时加入一个起息日入参
        params.bankStartDate = withdrawnInfo.bankStartDate;
        //交易录入支取时 若提前支取利率不存在 则用持仓数据的存款利率
        if (params.advanceInterestrate === null) params.advanceInterestrate = withdrawnInfo.bankDepositRate;
      }
    } else if (instructType == 'calc') {
      //结息
      args.bankDepositNumber = calcInterestInfo.pid;
      params.earlyDrawdownDate = moment(params.earlyDrawdownDate).format('YYYYMMDD');
      if (state == 10) {
        //交易录入时加入一个起息日入参
        params.bankStartDate = calcInterestInfo.bankStartDate;
      }
    } else {
      //存款
      C_CUSTODIAN.map((item) => {
        if (item.value == params.bankTrusteeshipQua) {
          params.bankTrusteeshipQua = item.code;
        }
      });
      params.earlyDrawdown = params.earlyDrawdown !== undefined ? (params.earlyDrawdown == '0' ? 'Y' : 'N') : params.earlyDrawdown;
      params.bankStartDate = moment(params.bankStartDate).format('YYYYMMDD');
      params.bankEndDate = params.bankEndDate ? moment(params.bankEndDate).format('YYYYMMDD') : undefined;
    }
    params.fee = this.props.state == 10 ? params.fee : 0; // (交易录入除外)费用计算逻辑未完全梳理清楚，后续用户有真正需求时再添加费用计算相关逻辑
    this.props.dispatch({
      type: url,
      payload: {
        ...params,
        combCode: state != 10 ? params.fundCode : params.combCode, //后端只需要一个组合id，不需要产品id，字段与前端的不一致，故修改
        userName: currentUser.name,
        userId: currentUser.userId,
        method: state == 1 ? undefined : 0, //0是新增 1是修改
        orderSize: instructType,
        ...args,
        uid: this.state.uid,
      },
      callback: (type, data) => {
        if (type == 'success') {
          let msg = instructType == 'F' ? '存入指令下达成功!' : instructType == 'i' ? '支取指令下达成功!' : '结息指令下达成功!';
          let msg1 = instructType == 'F' ? '存入簿记下达成功!' : instructType == 'i' ? '支取簿记下达成功!' : '结息簿记下达成功!';
          let msg2 = instructType == 'F' ? '存入组合试算下达成功!' : instructType == 'i' ? '支取组合试算下达成功!' : '结息组合试算下达成功!';

          message.success(state == 1 ? msg : state == 2 ? msg1 : state == 11 ? msg2 : '交易录入成功!');

          if (state == 2 || state == 10 || state == 11) {
            //簿记下达成功
            this.props.onOk();
          }
          this.cancelClick(); //初始化form表单
        } else {
          let msg = instructType == 'F' ? data.message || '存入指令下达失败!' : instructType == 'i' ? data.message || '支取指令下达失败!' : data.message || '结息指令下达失败!';
          let msg1 = instructType == 'F' ? data.message || '存入簿记下达失败!' : instructType == 'i' ? data.message || '支取簿记下达失败!' : data.message || '结息簿记下达失败!';
          let msg2 =
            instructType == 'F'
              ? data.errorMsg || '存入组合试算下达失败!'
              : instructType == 'i'
              ? data.errorMsg || '支取组合试算下达失败!'
              : data.errorMsg || '结息组合试算下达失败!';
          let msg3 = instructType == 'F' ? data.message || '交易录入失败!' : instructType == 'i' ? data.message || '交易录入失败!!' : data.message || '交易录入失败!!';
          message.error(state == 1 ? msg : state == 2 ? msg1 : state == 11 ? msg2 : msg3);
        }
        const uid = uniqueKey();
        uid.then((r) => {
          this.setState({ uid: r });
        });
      },
    });
  };
  //点击取消 重置
  cancelClick = () => {
    const { instructType } = this.state;
    if (this.props.state == 10 || this.props.state == 11) {
      //组合试算 交易录入点击取消 抛出oncancel事件
      this.props.onCancel();
      return;
    }
    //簿记、指令下达成功之后刷新时间戳
    this.setState({
      timeStamp: new Date().getTime(), //时间戳
      fundCode: undefined, //清空当前组合id
      flag: true,
    });
    //将所在的tab对应的组合id清空
    if (instructType == 'F') {
      //存
      this.setState(
        {
          saveOrderInfo: undefined,
          fundCodeSave: undefined,
        },
        () => {
          this.SaveOrder.reset();
        },
      );
    } else if (instructType == 'i') {
      //取
      this.WithdrawnOrder.reset();
      this.setState(
        {
          withdrawnInfo: undefined,
          fundCodeWithdrawn: undefined,
        },
        () => {
          this.WithdrawnOrder.reset();
        },
      );
    } else {
      //结息
      this.setState(
        {
          calcInterestInfo: undefined,
          fundCodeCalc: undefined,
        },
        () => {
          this.calcInterestOrder.reset();
        },
      );
    }
  };
  //tab切换 判断组合id
  tabChangeFundCode = (type) => {
    if (this.state[type] != this.state.fundCode) {
      this.setState({
        fundCode: this.state[type],
      });
    }
  };
  //tab 判断产品id
  tabChangeProductId = (type) => {
    if (this.state[type] != this.state.productId) {
      this.setState({
        productId: this.state[type],
      });
    }
  };

  //试算按钮点击
  trialOnClick = () => {
    const { instructType } = this.state;
    if (this.props.state != 10) {
      var T0 = this.CurrentAsset.state.assetObj.T0 || 0;
    }
    if (instructType == 'F') {
      //存
      this.SaveOrder.formContent.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          if (values.bankDepositBalance > T0) {
            message.error('存款金额不能大于T+0资金');
            return;
          }
          this.trailOnOk(values);
        }
      });
    } else if (instructType == 'i') {
      //取
      this.WithdrawnOrder.formContent.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          if (values.bankDrawDownBalance > values.bankDepositBalance) {
            message.error('支取本金不能大于存入金额');
            return;
          }
          this.trailOnOk(values);
        }
      });
    } else {
      //结息
      this.calcInterestOrder.formContent.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          if (values.bankDrawDownBalance > values.bankDepositBalance) {
            message.error('结息金额不能大于存入金额');
            return;
          }
          this.trailOnOk(values);
        }
      });
    }
  };
  trailOnOk = (params) => {
    const {
      dispatch,
      type,
      user: { currentUser = {} },
      globalM: {
        dataDictionary: { C_CUSTODIAN = [] },
      },
      state,
    } = this.props;
    const { instructType, withdrawnInfo, calcInterestInfo, productCode, portfolioCode, vcBankName } = this.state;
    const { headBankList } = this.state;
    let args = {}; //支取 结息的时候需要存款编号、相关存款的id
    if (instructType == 'i') {
      args.bankDepositNumber = withdrawnInfo.pid;
      params.earlyDrawdownDate = moment(params.earlyDrawdownDate).format('YYYYMMDD');
    } else if (instructType == 'calc') {
      //结息
      args.bankDepositNumber = calcInterestInfo.pid;
      params.earlyDrawdownDate = moment(params.earlyDrawdownDate).format('YYYYMMDD');
    } else {
      //存款
      C_CUSTODIAN.map((item) => {
        if (item.value == params.bankTrusteeshipQua) {
          params.bankTrusteeshipQua = item.code;
        }
      });
      params.earlyDrawdown = params.earlyDrawdown !== undefined ? (params.earlyDrawdown == '0' ? 'Y' : 'N') : params.earlyDrawdown;
      params.bankStartDate = moment(params.bankStartDate).format('YYYYMMDD');
      params.bankEndDate = params.bankEndDate ? moment(params.bankEndDate).format('YYYYMMDD') : undefined;
    }
    let querys = {
      productCode: productCode, //产品code
      portfolioCode: portfolioCode, //组合code
      tenant: currentUser.tenant, //租户code
      businessType: '8',
      method: state == 1 ? undefined : 0, //0是新增 1是修改
      type: '8',
      trade8: {
        ...params,
        combCode: state != 10 ? params.fundCode : params.combCode, //后端只需要一个组合id，不需要产品id，字段与前端的不一致，故修改
        userName: currentUser.name,
        userId: currentUser.userId,
        method: state == 1 ? undefined : 0, //0是新增 1是修改
        orderSize: instructType,
        vcBankName: headBankList?.filter((item) => item.bankNo == params.bankHeadOfficeName)[0]?.bankName,
        ...args,
      },
    };
    this.setState({ trailModel: true }, () => {
      dispatch({
        type: 'trailM/trialData',
        payload: querys,
        callback: (res) => {
          if (res) {
            this.setState({
              trailColumns: res.columns,
              trailDataSource: res.dataSource,
            });
          } else {
            this.setState({
              trailColumns: [],
              trailDataSource: [],
            });
          }
        },
      });
    });
  };
  //试算结果列表优化
  trailColumnsChange = (data) => {
    if (data) {
      data?.map((item) => {
        if (item.key == 'ruleDesc') {
          item.ellipsis = true;
        } else {
          item.width = '125px';
        }
      });
    }
    return data;
  };
  //试算结果
  showTrail = () => {
    const { trailModel, trailColumns, trailDataSource } = this.state;
    const newTrailColumns = this.trailColumnsChange(trailColumns);
    return (
      <ModalC
        visible={trailModel}
        title='试算结果'
        width={1200}
        onOk={() => {
          this.setState({ trailModel: false });
        }}
        onCancel={() => {
          this.setState({ trailModel: false });
        }}
      >
        <TableC
          columns={newTrailColumns}
          dataSource={trailDataSource}
          loading={this.props.loading.effects['trailM/trialData'] === true}
          scroll={{ y: '231px' }}
          rowKey='id'
          hidePage={true}
        />
      </ModalC>
    );
  };
  //获取组合code
  portfolioCode = (e) => {
    if (e) {
      this.setState({ portfolioCode: e });
    } else this.setState({ portfolioCode: undefined });
  };
  //获取产品code
  productCode = (e) => {
    this.setState({
      flag: true,
      fundCode: undefined,
    });
    if (e) {
      this.setState({ productCode: e });
    } else this.setState({ productCode: undefined });
  };
  //存款总行
  vcBankName = (data) => {
    this.setState({
      headBankList: data,
    });
  };
  render() {
    const { timeStamp, fundCode, headBankList, saveOrderInfo, withdrawnInfo, typeList, calcInterestInfo, flag } = this.state;
    const { loading, state } = this.props;
    const initComp = (key) => {
      if (key === 'F')
        return (
          <SaveOrder
            state={state}
            typeList={typeList}
            onRef={(ref) => (this.SaveOrder = ref)}
            listId={this.props.listId}
            getFundCode={(e) => this.getFundCode(e, 'fundCodeSave')}
            getProductCode={(e) => this.getProductCode(e, 'productIdSave')}
            portfolioCode={this.portfolioCode}
            productCode={this.productCode}
            vcBankName={this.vcBankName}
            depositInfo={saveOrderInfo}
          />
        );

      if (key === 'i')
        return (
          <WithdrawnOrder
            state={state}
            typeList={typeList}
            listId={this.props.listId}
            getFundCode={(e) => this.getFundCode(e, 'fundCodeWithdrawn')}
            getProductCode={(e) => this.getProductCode(e, 'productIdWithdrawn')}
            portfolioCode={this.portfolioCode}
            productCode={this.productCode}
            vcBankName={this.vcBankName}
            onRef={(ref) => (this.WithdrawnOrder = ref)}
            depositInfo={withdrawnInfo}
          />
        );
      if (key === 'calc')
        return (
          <CalcInterestOrder
            state={state}
            typeList={typeList}
            listId={this.props.listId}
            getFundCode={(e) => this.getFundCode(e, 'fundCodeCalc')}
            getProductCode={(e) => this.getProductCode(e, 'productIdCalc')}
            portfolioCode={this.portfolioCode}
            productCode={this.productCode}
            vcBankName={this.vcBankName}
            onRef={(ref) => (this.calcInterestOrder = ref)}
            depositInfo={calcInterestInfo}
          />
        );
    };
    return (
      <div className={style.addNew}>
        <Spin
          spinning={
            loading.effects[`depositOrderM/orderSave`] == true ||
            loading.effects[`depositOrderM/tradeBookSave`] == true ||
            loading.effects[`depositOrderM/tradeAdd`] == true ||
            loading.effects['portfolioTrialAddM/addNewSave'] == true
          }
        >
          {this.props.state != 10 ? (
            <>
              <div>
                <FirstHeaderC title='当前资金' />
              </div>
              <div style={{ position: 'relative' }}>
                <CurrentAsset onRef={(ref) => (this.CurrentAsset = ref)} timeStamp={timeStamp} fundCode={fundCode} />
                {flag && (
                  <div>
                    <NoDataMaskC height='50px' title={'请选择相对应组合，加载数据！'} />
                  </div>
                )}
              </div>
            </>
          ) : null}
          <div>
            <FirstHeaderC title='当前持仓' />
          </div>
          <div style={{ position: 'relative' }}>
            <Hold timeStamp={timeStamp} headBankList={[]} typeList={typeList} fundCode={fundCode} productId={this.state.productId} type={state} doubleClick={this.holdClick} />
            {this.props.state != 10 && flag && (
              <div>
                <NoDataMaskC height='45px' title={'请选择相对应组合，加载数据！'} />
              </div>
            )}
          </div>
          <div style={{ marginTop: '10px' }}>
            <FirstHeaderC title='交易要素' />
          </div>
          <div className={'grayBg'}>
            <Tabs
              onChange={(val) => {
                this.setState({ instructType: val });
                if (val == 'F') {
                  //拿激活的tab的组合ID与当前组合ID相比较，如果不一样，则更新当前组合ID
                  this.tabChangeFundCode('fundCodeSave');
                  this.tabChangeProductId('productIdSave');
                } else if (val == 'i') {
                  this.tabChangeFundCode('fundCodeWithdrawn');
                  this.tabChangeProductId('productIdWithdrawn');
                } else {
                  this.tabChangeFundCode('fundCodeCalc');
                  this.tabChangeProductId('productIdCalc');
                }
              }}
            >
              {config.tabList.map((item) => {
                return (
                  <TabPane tab={item.title} key={item.key}>
                    {initComp(item.key)}
                  </TabPane>
                );
              })}
            </Tabs>
          </div>
          <div className={'btnOperate grayBg'}>
            {/* {state == "2" && <PrimaryC
              loading={loading.effects['trailM/trialData'] === true}
              onClick={() => this.trialOnClick()}
              title={'试算'}
              style={{ marginRight: "10px" }}
            />} */}
            <PrimaryC title={this.props.state == 1 ? '指令下达' : '确定'} onClick={this.confirmClick} />
            <PrimaryGhostC title={'取消'} onClick={this.cancelClick} style={{ marginLeft: '10px' }} />
          </div>
        </Spin>
        {this.state.trailModel && this.showTrail()}
      </div>
    );
  }
}
